<?php

namespace App\Http\Controllers\Agent;

use App\Exceptions\BizException;
use App\Http\Controllers\Controller;
use App\Model\Cate;
use App\Model\Goods;
use App\Model\GoodsAttr;
use App\Model\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class GoodsController extends Controller
{
    public $agent;

    public function __construct()
    {
        $this->middleware(['agent']);
        $this->agent = Auth::guard('agent')->user();
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $model = Goods::where('status', '>', '-1')->where('agent_id', $this->agent->id);
        !empty($params['supplier_id']) && $model->where('supplier_id', $params['supplier_id']);
        !empty($params['cate_id']) && $model->where('cate_id', $params['cate_id']);
        !empty($params['name']) && $model->where('name', 'like', "%{$params['name']}%");
        isset($params['status']) && $params['status'] !== '' && $model->where('status', $params['status']);
        isset($params['is_home']) && $params['is_home'] !== '' && $model->where('is_home', $params['is_home']);
        $list = $model->orderBy('order_num', 'desc')->orderBy('id', 'desc')->paginate(15);
        return view('agent.goods.index', [
            'list' => $list,
            'cateNames' => Cate::getCateNames($this->agent->id, true),
            'params' => $params,
            'suppliers' => Supplier::getSupplierNames($this->agent->id),
        ]);
    }

    public function add(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'supplier_id' => 'required',
                    'cate_id' => 'required',
                    'name' => 'required',
                    'pic' => 'required',
                    'cost' => 'required|numeric',
                    'origin_price' => 'required|numeric',
                    'price' => 'required|numeric',
                    'detail' => 'required',
                ], [
                    'supplier_id.required' => '请选择供应商',
                    'cate_id.required' => '请选择商品分类',
                    'name.required' => '商品名必填',
                    'pic.required' => '请上传商品的图片',
                    'cost.required' => '成本价必填',
                    'cost.numeric' => '成本价必须是数值',
                    'origin_price.required' => '原价必填',
                    'origin_price.numeric' => '原价必须是数值',
                    'price.required' => '现价必填',
                    'price.numeric' => '现价必须是数值',
                    'detail.required' => '商品详情必填',
                ]);

                $params = $request->all();
                $row = Goods::where('agent_id', $this->agent->id)->where('name', $params['name'])->first();
                if ($row)
                    throw new BizException('该商品已存在');

                $params['agent_id'] = $this->agent->id;
                $params['status'] = Goods::STATUS_0;
                $goodModel = Goods::create($params);

                // 保存规格
                $attr = empty($params['attr']) ? [] : $params['attr'];
                GoodsAttr::saveAttr($goodModel->id, $attr);
                return response()->json(['status' => 1, 'info' => '保存成功']);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            return view('agent.goods.add', [
                'cateNames' => Cate::getCateNames($this->agent->id),
                'suppliers' => Supplier::getSupplierNames($this->agent->id),
            ]);
        }
    }

    public function edit(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'supplier_id' => 'required',
                    'cate_id' => 'required',
                    'name' => 'required',
                    'pic' => 'required',
                    'cost' => 'required|numeric',
                    'origin_price' => 'required|numeric',
                    'price' => 'required|numeric',
                    'detail' => 'required',
                ], [
                    'supplier_id.required' => '请选择供应商',
                    'cate_id.required' => '请选择商品分类',
                    'name.required' => '商品名必填',
                    'pic.required' => '请上传商品的图片',
                    'cost.required' => '成本价必填',
                    'cost.numeric' => '成本价必须是数值',
                    'origin_price.required' => '原价必填',
                    'origin_price.numeric' => '原价必须是数值',
                    'price.required' => '现价必填',
                    'price.numeric' => '现价必须是数值',
                    'detail.required' => '商品详情必填',
                ]);

                $params = $request->all();
                $id = $params['id'];
                $attr = empty($params['attr']) ? [] : $params['attr'];

                $row = Goods::where('agent_id', $this->agent->id)->where('id', '!=', $id)->where('name', $params['name'])->first();
                if ($row)
                    throw new BizException('该商品已存在');

                if (isset($params['id']))
                    unset($params['id']);
                if (isset($params['attr']))
                    unset($params['attr']);
                Goods::where('id', $id)->update($params);
                GoodsAttr::saveAttr($id, $attr); // 保存规格
                return response()->json(['status' => 1, 'info' => '保存成功']);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            $row = Goods::find($request->input('id'));
            if ($row['agent_id'] != $this->agent->id)
                return '你无权修改';

            return view('agent.goods.edit', [
                'cateNames' => Cate::getCateNames($this->agent->id),
                'suppliers' => Supplier::getSupplierNames($this->agent->id),
                'attr' => GoodsAttr::getAttrByGoodsId($request->input('id')),
                'row' => $row,
            ]);
        }
    }

    public function changeStatus(Request $request)
    {
        $goods = Goods::find($request->input('id'));
        if ($goods['agent_id'] != $this->agent->id)
            return response()->json(['status' => 0, 'info' => '您无权做此操作']);

        Goods::where('id', $request->input('id'))->update(['status' => $request->input('status')]);
        return response()->json(['status' => 1, 'info' => '操作成功']);
    }
}